package com.wsc.springbootmultidevdemo.springMsg;


import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

/**
 * text 类型消息转换
 */
public class TextMessageConverter implements MessageConverter {
    /**
     * 给 broker 发送消息时把消息转换成 broker 识别的 Message 类型
     * @param o 消息
     * @param messageProperties 消息参数
     * @return 转换后的 message
     * @throws MessageConversionException
     */
    @Override
    public Message toMessage(Object o, MessageProperties messageProperties) throws MessageConversionException {
        Message message = new Message(o.toString().getBytes(), messageProperties);
        return message;
    }

    /**
     * 将 broker 发送来的 含 text 的 Message 转换成 String 类型
     * @param message
     * @return
     * @throws MessageConversionException
     */
    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        String contentType = message.getMessageProperties().getContentType();
        if(contentType != null && contentType.contains("text")){
            String msg = new String(message.getBody());
            return msg;
        }else {
            return message.getBody();
        }
    }
}
